home *** CD-ROM | disk | FTP | other *** search
- \chapter{Overview}
- \section{Starting SWI-Prolog from the Unix Shell}
- It is advised to install SWI-Prolog as `pl' in the local binary
- directory. SWI-Prolog can then be started from the Unix shell by typing
- `\file{pl}'. The system will boot from the system's default boot
- file, perform the necessary initialisations and then enter the
- interactive top level.
- After the necessary system initialisation the system consults (see
- consult/1) the user's initialisation file. This initialisation file
- should be named `\file{.plrc}' and reside either in the current
- directory or in the user's home directory. If both exist the
- initialisation file from the current directory is loaded. The name of
- the initialisation file can be changed with the `\argoption{-f}{file}'
- option. After loading the initialisation file SWI-Prolog executes a user
- initialisation goal. The default goal is a system predicate that prints
- the banner message. The default can be modified with the
- `\argoption{-g}{goal}' option. Next the toplevel goal is started.
- Default is the interactive Prolog loop (see prolog/0). The user can
- overwrite this default with the `\argoption{-t}{toplevel}' option.
- \subsection{Command Line Options}
- The full set of command line options is given below:
- \begin{description}
- \cmdlineoptionitem{-help}{}
- When given as the only option, it summarises the most important options.
- \cmdlineoptionitem{-v}{}
- When given as the only option, it summarises the version and the
- architecture identifier.
- \cmdlineoptionitem{-arch}{}
- When given as the only option, it prints the architecture identifier
- (see feature(arch, Arch)) and exits.
- \cmdlineoptionitem*{-L}{size[km]}
- Give local stack limit (2 Mbytes default). Note that there is no space
- between the size option and its argument. By default, the argument is
- interpreted in Kbytes. Postfixing the argument with \const{m} causes
- the argument to be interpreted in Mbytes. The following example
- specifies 32 Mbytes local stack.
- \begin{code}
- % pl -L32m
- \end{code}
- A maximum is useful to stop buggy programs from claiming all memory
- resources. \cmdlineoption{-L0} sets the limit to the highest possible
- value.
- \cmdlineoptionitem*{-G}{size[km]}
- Give global stack limit (4 Mbytes default). See \cmdlineoption{-L} for
- more details.
- \cmdlineoptionitem*{-T}{size[km]}
- Give trail stack limit (4 Mbytes default). This limit is relatively high
- because trail-stack overflows are not often caused program bugs. See
- \cmdlineoption{-L} for more details.
- \cmdlineoptionitem*{-A}{size[km]}
- Give argument stack limit (1 Mbytes default). The argument stack limits
- the maximum nesting of terms that can be compiled and executed. The
- SWI-Prolog does `last-argument optimisation' to avoid many deeply nested
- structure using this stack. Enlarging this limit is only necessary in
- extreme cases. See \cmdlineoption{-L} for more details.
- \cmdlineoptionitem*{-H}{size[km]}
- Give \funcref{malloc}{} heap limit. The default is to raise the limit as
- high as possible. This option only applies to machines using the
- \funcref{mmap}{} function for allocating the Prolog stacks. See
- \cmdlineoption{-L} for more details.
- \cmdlineoptionitem{-c}{file \ldots}
- Compile files into an `intermediate code file'. See \secref{compilation}.
- \cmdlineoptionitem{-o}{output}
- Used in combination with \cmdlineoption{-c} or \cmdlineoption{-b} to
- determine output file for compilation.
- \cmdlineoptionitem{-O}{}
- Optimised compilation. See please/3.
- \cmdlineoptionitem{-f}{file}
- Use \arg{file} as initialisation file instead of `\file{.plrc}'.
- `\argoption{-f}{none}' stops SWI-Prolog from searching for an
- initialisation file.
- \cmdlineoptionitem{-F}{script}
- Selects a startup-script from the SWI-Prolog home directory. The
- script-file is named \file{<script>.rc}. The default
- \arg{script} name is deduced from the executable, taking the leading
- alphanumerical characters (letters, digits and underscore) from the
- program-name. \argoption{-F}{none} stops looking for a script. Intended
- for simple management of slightly different versions. One could for
- example write a script \file{iso.rc} and then select ISO compatibility
- mode using \exam{pl -F iso} or make a link from \program{iso-pl} to
- \program{pl}.
- \cmdlineoptionitem{-g}{goal}
- \arg{Goal} is executed just before entering the top level. Default is a
- predicate which prints the welcome message. The welcome message can
- thus be suppressed by giving \argoption{-g}{true}. \arg{goal} can be a complex
- term. In this case quotes are normally needed to protect it from
- being expanded by the Unix shell.
- \cmdlineoptionitem{-t}{goal}
- Use \arg{goal} as interactive toplevel instead of the default goal
- prolog/0. \arg{goal} can be a complex term. If the toplevel goal
- succeeds SWI-Prolog exits with status 0. If it fails the exit status is 1.
- This flag also determines the goal started by break/0 and abort/0. If
- you want to stop the user from entering interactive mode start the
- application with `\argoption{-g}{goal}' and give `halt' as toplevel.
- \cmdlineoptionitem{-tty}{}
- Switches tty control (using ioctl(2)) on (\cmdlineoption{+tty}) or off
- (\cmdlineoption{-tty}). Normally tty control is switched on. This default
- depends on the installation. You may wish to switch tty control off if
- Prolog is used from an editor such as Emacs. If switched off
- get_single_char/1 and the tracer will wait for a return.
- \cmdlineoptionitem{-x}{bootfile}
- Boot from \arg{bootfile} instead of the system's default boot file. A
- bootfile is a file resulting from a Prolog compilation using the
- \cmdlineoption{-b} or \cmdlineoption{-c} option or a program saved using
- qsave_program/[1,2].
- \cmdlineoptionitem{-r}{restorefile}
- Restore a state created by save_program/[1,2] or save/[1,2] using
- the new-style saved-states. Equivalent to \exam{restore(restorefile)} from
- Prolog.
- \cmdlineoptionitem{-p}{alias=path1[:path2 \ldots]}
- Define a path alias for file_search_path. \arg{alias} is the name of
- the alias, \arg{path1 ...} is a \chr{:} separated list of values for
- the alias. A value is either a term of the form \mbox{alias(value)}
- or pathname. The computed aliases are added to file_search_path/2
- using asserta/1, so they precede predefined values for the alias. See
- file_search_path/2 for details on using this file-location mechanism.
- \cmdlineoptionitem{{\tt --}}{}
- Stops scanning for more arguments, so you can pass arguments for your
- application after this one.
- \end{description}
- The following options are for system maintenance. They are given
- for reference only.
- \begin{description}
- \cmdlineoptionitem{-b}{initfile \ldots \cmdlineoption{-c} file \ldots}
- Boot compilation. \arg{initfile \ldots} are compiled by the C-written
- bootstrap compiler, \arg{file \ldots} by the normal Prolog compiler.
- System maintenance only.
- \cmdlineoptionitem{-d}{level}
- Set debug level to \arg{level}. Only has effect if the system is
- compiled with the \const{-DO_DEBUG} flag. System maintenance
- only.
- \end{description}
- \section{GNU Emacs Interface}
- \index{GNU-Emacs}\index{Emacs}
- A provisional interface to \program{emacs} has been included since
- version 1.6 of SWI-Prolog. The interface is based on the freely
- distributed interface delivered with Quintus Prolog. When running Prolog
- as an inferior process under GNU-Emacs, there is support for finding
- predicate definitions, completing atoms, finding the locations of
- compilation-warnings and many more. For details, see the files
- \file{pl/lisp/README} and \file{pl/lisp/swi-prolog.el}.
- \section{Online Help}
- Online help provides a fast lookup and browsing facility to this
- manual. The online manual can show predicate definitions as well as
- entire sections of the manual.
- The online help is displayed from the file \pllib{'MANUAL'}. The file
- \pllib{helpidx} provides an index into this file. \pllib{'MANUAL'} is
- created from the \LaTeX{} sources with a modified version of
- \program{dvitty}, using overstrike for printing bold text and
- underlining for rendering italic text. XPCE is shipped with
- \pllib{swi_help}, presenting the information from the online help in a
- hypertext window. The feature \const{write_help_with_overstrike}
- controls whether or not help/1 writes its output using overstrike to
- realise bold and underlined output or not. If this feature is not set it
- is initialised by the help library to \const{true} if the \const{TERM}
- variable equals \const{xterm} and \const{false} otherwise. If this
- default does not satisfy you, add the following line to \file{~/.plrc}.
- \begin{code}
- :- set_feature(write_help_with_overstrike, true).
- \end{code}
- \begin{description}
- \predicate{help}{0}{}
- Equivalent to \exam{help(help/1)}.
- \predicate{help}{1}{+What}
- Show specified part of the manual. \arg{What} is one of:
- \begin{center}\begin{tabular}{lp{3.5in}}
- <Name>/<Arity> & give help on specified predicate \\
- <Name> & give help on named predicate with any arity
- or C interface function with that name \\
- <Section> & display specified section. section numbers are
- dash-separated numbers: \exam{2-3} refers to
- section 2.3 of the manual. Section numbers are
- obtained using apropos/1.
- \end{tabular}\end{center}
- Examples
- \begin{center}\begin{tabular}{lp{3.5in}}
- \exam{?- help(assert).} & give help on predicate assert \\
- \exam{?- help(3-4).} & display section 3.4 of the manual \\
- \exam{?- help('PL_retry').}& give help on interface function PL_retry() \\
- \end{tabular}\end{center}
- \predicate{apropos}{1}{+Pattern}
- Display all predicates, functions and sections that have {\em
- Pattern} in their name or summary description. Lowercase letters in
- \arg{Pattern} also match a corresponding uppercase letter. Example:
- \begin{center}\begin{tabular}{lp{3.5in}}
- \exam{?- apropos(file).} & Display predicates, functions and sections
- that have `file' (or `File', etc.) in their
- summary description. \\
- \end{tabular}\end{center}
- \predicate{explain}{1}{+ToExplain}
- Give an explanation on the given `object'. The argument may be
- any Prolog data object. If the argument is an atom, a term of
- the form \arg{Name/Arity} or a term of the form {\em
- Module:Name/Arity}, explain will try to explain the predicate
- as well as possible references to it.
- \predicate{explain}{2}{+ToExplain, -Explanation}
- Unify \arg{Explanation} with an explanation for \arg{ToExplain}.
- Backtracking yields further explanations.
- \end{description}
- \section{Query Substitutions}
- \label{sec:history}
- SWI-Prolog offers a query substitution mechanism similar to that of Unix
- csh (csh(1)), called `history'. The availability of this feature is
- controlled by set_feature/2, using the \const{history} feature. By
- default, history is available if the feature \const{readline} is
- \const{false}. To enable this feature, remembering the last 50 commands,
- put the following into your \file{~/.plrc} file:
- \begin{code}
- :- set_feature(history, 50).
- \end{code}
- The history system allows the user to compose new queries from those
- typed before and remembered by the system. It also allows to correct
- queries and syntax errors. SWI-Prolog does not offer the Unix csh
- capabilities to include arguments. This is omitted as it is unclear how
- the first, second, etc.\ argument should be defined.%
- \footnote{One could choose words, defining words as a sequence of
- alpha-numeric characters and the word separators as
- anything else, but one could also choose Prolog
- arguments}
- The available history commands are shown in \tabref{history}.
- \Figref{history} gives some examples.
- \begin{table}
- \begin{center}
- \begin{tabular}{|l|l|}
- \hline
- \verb+!!.+ & Repeat last query \\
- \verb+!nr.+ & Repeat query numbered <nr> \\
- \verb+!str.+ & Repeat last query starting with <str> \\
- \verb+!?str.+ & Repeat last query holding <str> \\
- \verb+^old^new.+ & Substitute <old> into <new> of
- last query \\
- \verb+!nr^old^new.+ & Substitute in query numbered <nr> \\
- \verb+!str^old^new.+ & Substitute in query starting with <str> \\
- \verb+!?str^old^new.+ & Substitute in query holding <str> \\
- \verb+h.+ & Show history list \\
- \verb+!h.+ & Show this list \\
- \hline
- \end{tabular}
- \end{center}
- \caption{History commands}
- \label{tab:history}
- \end{table}
- \begin{figure}
- \begin{code}
- /staff/jan/.plrc consulted, 0.066667 seconds, 591 bytes
- Welcome to SWI-Prolog (Version \plversion)
- Copyright (c) 1993-1996 University of Amsterdam. All rights reserved.
- For help, use ?- help(Topic). or ?- apropos(Word).
- 1 ?- append("Hello ", "World", L).
- L = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
- 2 ?- !!, writef('L = %s\n', [L]).
- append("Hello ", "World", L), writef('L = %s\n', [L]).
- L = Hello World
- L = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
- 3 ?- sublist(integer, [3, f, 3.4], L).
- L = [3]
- 4 ?- ^integer^number.
- sublist(number, [3, f, 3.4], L).
- L = [3, 3.400000]
- 5 ?- h.
- 1 append("Hello ", "World", L).
- 2 append("Hello ", "World", L), writef('L = %s\n', [L]).
- 3 sublist(integer, [3, f, 3.4], L).
- 4 sublist(number, [3, f, 3.4], L).
- 5 ?- !2^World^Universe.
- append("Hello ", "Universe", L), writef('L = %s\n', [L]).
- L = Hello Universe
- L = [72, 101, 108, 108, 111, 32, 85, 110, 105, 118, 101, 114, 115, 101]
- 6 ?- halt.
- \end{code}
- \caption{Some examples of the history facility}
- \label{fig:history}
- \end{figure}
- \subsection{Limitations of the History System}
- When in top level SWI-Prolog reads the user's queries using
- read_history/6 rather than read/1. This predicate first reads the
- current input stream up to a full stop. While doing so it maps all
- contiguous blank space onto a single space and deletes
- \exam{/* \ldots */} and \exam{\% \ldots <cr>} comments. Parts between double quotes
- (\const{"}) or single quotes (\const{'}) are left unaltered. Note that a
- Prolog full stop consists of a `non-symbol' character, followed by a
- period (\const{.}), followed by a blank character. `Symbol' characters
- are: \verb!#$&*+-./:<=>?@^`~!. A single quote immediately preceded by
- a digit (0-9) is considered part of the \mbox{<digit>'<digit>\ldots}
- (e.g.\ \exam{2'101}; binary number 101) sequence.
- After this initial parsing the result is first checked for the special
- \mbox{\Shat<old>\Shat<new>.} construction. If this fails the
- string is checked for all occurrences of the \const{!}, followed by a
- \const{!}, \const{?}, a digit, a letter or an underscore. These special
- sequences are analysed and the appropriate substitution from the history
- list is made.
- From the above it follows that it is hard or impossible to
- correct quotation with single or double quotes, comment delimiters and
- spacing.
- \section{Reuse of toplevel bindings} \label{sec:topvars}
- Bindings resulting from the successful execution of a toplevel goal
- are asserted in a database. These values may be reused in further
- toplevel queries as \$Var. Only the latest binding is available.
- Example:
- \begin{figure}
- \begin{code}
- 1 ?- maplist(plus(1), "hello", X).
- X = [105,102,109,109,112]
- 2 ?- format('~s~n', [$X]).
- ifmmp
- \end{code}
- \caption{Reusing toplevel bindings}
- \label{fig:topevelvars}
- \end{figure}
- Note that variables may be set by executing \predref{=}{2}:
- \begin{code}
- 6 ?- X = statistics.
- X = statistics
- 7 ?- $X.
- 28.00 seconds cpu time for 183,128 inferences
- 4,016 atoms, 1,904 functors, 2,042 predicates, 52 modules
- 55,915 byte codes; 11,239 external references
- Limit Allocated In use
- Heap : 624,820 Bytes
- Local stack : 2,048,000 8,192 404 Bytes
- Global stack : 4,096,000 16,384 968 Bytes
- Trail stack : 4,096,000 8,192 432 Bytes
- \end{code}
- \section{Overview of the Debugger}
- SWI-Prolog has a 6-port tracer, extending the standard 4-port tracer
- \cite{Clocksin:87} with two additional ports. The optional \arg{unify}
- port allows the user to inspect the result after unification of the
- head. The \arg{exception} port shows exceptions raised by throw/1
- or one of the built-in predicates. See \secref{exception}.
- The standard ports are called \const{call}, \const{exit}, \const{redo},
- \const{fail} and \const{unify}. The tracer is started by the trace/0
- command, when a spy point is reached and the system is in debugging mode
- (see spy/1 and debug/0) or when an exception is raised.
- The interactive toplevel goal trace/0 means ``trace the next query''.
- The tracer shows the port, displaying the port name, the current depth
- of the recursion and the goal. The goal is printed using the Prolog
- predicate print/1 (default), write/1 or display/1. An example using all
- ports is shown in \figref{tracer}.
- \begin{figure}
- \begin{code}
- 2 ?- visible(+all), leash(-exit).
- 3 ?- trace, min([3, 2], X).
- Call: ( 3) min([3, 2], G235) ? creep
- Unify: ( 3) min([3, 2], G235)
- Call: ( 4) min([2], G244) ? creep
- Unify: ( 4) min([2], 2)
- Exit: ( 4) min([2], 2)
- Call: ( 4) min(3, 2, G235) ? creep
- Unify: ( 4) min(3, 2, G235)
- Call: ( 5) 3 < 2 ? creep
- Fail: ( 5) 3 < 2 ? creep
- Redo: ( 4) min(3, 2, G235) ? creep
- Exit: ( 4) min(3, 2, 2)
- Exit: ( 3) min([3, 2], 2)
- \end{code}
- \caption{Example trace}
- \label{fig:tracer}
- \end{figure}
- On {\em leashed ports} (set with the predicate leash/1, default are
- \const{call}, \const{exit}, \const{redo} and \const{fail}) the user is
- prompted for an action. All actions are single character commands which
- are executed {\bf without} waiting for a return, unless the command line
- option \cmdlineoption{-tty} is active. Tracer options:
- \begin{description}
- \traceoption{+}{Spy}{
- Set a spy point (see spy/1) on the current predicate.}
- \traceoption{-}{No spy}{
- Remove the spy point (see nospy/1) from the current predicate.}
- \traceoption{/}{Find}{
- Search for a port. After the `/', the user can enter a line
- to specify the port to search for. This line consists of a set of
- letters indicating the port type, followed by an optional term,
- that should unify with the goal run by the port. If no term is
- specified it is taken as a variable, searching for any port of the
- specified type. If an atom is given, any goal whose functor has a
- name equal to that atom matches. Examples:
- \begin{center}\begin{tabular}{lp{3in}}
- \tt /f & Search for any fail port \\
- \tt /fe solve & Search for a fail or exit port of any goal with
- name \const{solve} \\
- \tt /c solve(a, _) & Search for a call to {solve}/2 whose first argument
- is a variable or the atom \const{a} \\
- \tt /a member(_, _) & Search for any port on member/2. This is equivalent
- to setting a spy point on member/2. \\
- \end{tabular}\end{center}}
- \traceoption{.}{Repeat find}{
- Repeat the last find command (see `/')}
- \traceoption{A}{Alternatives}{
- Show all goals that have alternatives.}
- \traceoption{C}{Context}{
- Toggle `Show Context'. If \const{on} the context module of the goal is
- displayed between square brackets (see \secref{modules}).
- Default is \const{off}.}
- \traceoption{L}{Listing}{
- List the current predicate with listing/1.}
- \traceoption{a}{Abort}{
- Abort Prolog execution (see abort/0).}
- \traceoption{b}{Break}{
- Enter a Prolog break environment (see break/0).}
- \traceoption{c}{Creep}{
- Continue execution, stop at next port. (Also return, space).}
- \traceoption{d}{Display}{
- Write goals using the Prolog predicate display/1.}
- \traceoption{e}{Exit}{
- Terminate Prolog (see halt/0).}
- \traceoption{f}{Fail}{
- Force failure of the current goal}
- \traceoption{g}{Goals}{
- Show the list of parent goals (the execution stack). Note that due to tail
- recursion optimization a number of parent goals might not exist any more.}
- \traceoption{h}{Help}{
- Show available options (also `?').}
- \traceoption{i}{Ignore}{
- Ignore the current goal, pretending it succeeded.}
- \traceoption{l}{Leap}{
- Continue execution, stop at next spy point.}
- \traceoption{n}{No debug}{
- Continue execution in `no debug' mode.}
- \traceoption{p}{Print}{
- Write goals using the Prolog predicate print/1 (default).}
- \traceoption{r}{Retry}{
- Undo all actions (except for database and i/o actions) back to the call
- port of the current goal and resume execution at the call port.}
- \traceoption{s}{Skip}{
- Continue execution, stop at the next port of {\bf this} goal (thus skipping
- all calls to children of this goal).}
- \traceoption{u}{Up}{
- Continue execution, stop at the next port of {\bf the parent} goal (thus
- skipping this goal and all calls to children of this goal). This option
- is useful to stop tracing a failure driven loop.}
- \traceoption{w}{Write}{
- Write goals using the Prolog predicate write/1.}
- \end{description}
- The ideal 4 port model as described in many Prolog books
- \cite{Clocksin:87} is not visible in many Prolog implementations because
- code optimisation removes part of the choice- and exit points.
- Backtrack points are not shown if either the goal succeeded
- deterministically or its alternatives were removed using the cut. When
- running in debug mode (debug/0) choice points are only destroyed when
- removed by the cut. In debug mode, tail recursion optimisation is
- switched off.%
- \footnote{This implies the system can run out of local stack in debug
- mode, while no problems arise when running in non-debug mode.}
- \section{Compilation} \label{sec:compilation}
- \subsection{During program development}
- During program development, programs are normally loaded using
- consult/1, or the list abreviation. It is common practice to organise a
- project as a collection of source-files and a \jargon{load-file}, a
- Prolog file containing only use_module/[1,2] or ensure_loaded/1
- directives, possibly with a definition of the \jargon{entry-point} of
- the program, the predicate that is normally used to start the program.
- This file is often called \file{load.pl}. If the entry-point is called
- {\em go}, a typical session starts as:
- \begin{code}
- <banner>
- 1 ?- [load].
- <compilation messages>
- 2 ?- go.
- <program interaction>
- \end{code}
- When using Windows, the user may open \file{load.pl} from the Windows
- explorer, which will cause \program{plwin.exe} to be started in the
- directory holding \file{load.pl}. Prolog loads \file{load.pl} before
- entering the toplevel.
- \subsection{For running the result}
- There are various options if you want to make your program ready
- for real usage. The best choice depends on whether the program
- is to be used only on machines holding the SWI-Prolog development
- system, the size of the program and the operating system (Unix
- vs.\ Windows).
- \subsubsection{Creating a shell-script}
- Especially on Unix systems and not-too-large applications, writing
- a shell-script that simply loads your application and calls the
- entry-point is often a good choice. A skeleton for the script is
- given below, followed by the Prolog code to obtain the program
- arguments.
- \begin{code}
- #!/bin/sh
- base=<absolute-path-to-source>
- PL=pl
- exec $PL -f none -g "load_files(['$base/load'],[silent(true)])" -t go -- $*
- \end{code}
- \begin{code}
- go :-
- unix(argv(Arguments)),
- append(_SytemArgs, [--|Args], Arguments), !,
- go(Args).
- go(Args) :-
- \end{code}
- On Windows systems, similar behaviour can be achieved by creating a
- shortcut to Prolog, passing the proper options or writing a \fileext{bat}
- file.
- \subsubsection{Creating a saved-state}
- For larger programs, as well as for programs that are required run on
- systems that do not have the SWI-Prolog development system installed,
- creating a saved state is the best solution. A saved state is created
- using qsave_program/[1,2] or using the linker plld(1). A saved state is
- a file containing machine-independent intermediate code in a format
- dedicated for fast loading. Optionally, the emulator may be integrated
- in the saved state, creating a single-file, but machine-dependent,
- exectable. This process is descriped in \chapref{runtime}.
- \subsubsection{Compililation using the -c commandline option}
- This mechanism is mostly for backward compatibility. It creates files in
- the same format as saved-states created using qsave_program/[1,2], but
- the resulting file is a translation of the source-files read, rather
- than a translation of the state of the machine. Unlike saved states,
- programs created using \argoption{-c}{file} do not include the Prolog
- part of the development system. The result is very dependent on the
- local SWI-Prolog installation.
- The command below is used to compile one or more source-files.
- \begin{code}
- pl [options] [-o output] -c file ...
- \end{code}
- The individual source files may include other files using the standard
- list notation, consult/1, ensure_loaded/1 and use_module/[1,2]. When the
- \argoption{-o}{file} option is omitted a file named \file{a.out} is
- created that holds the intermediate code file.
- Intermediate code files start with the Unix magic code \const{#!}
- and are executable. This implies they can be started as a command:
- \begin{code}
- % pl -o my_program -c ...
- % my_program [options]
- \end{code}
- Alternatively, {\tt my_program} can be started with
- \begin{code}
- % pl -x my_program [options]
- \end{code}
- The following restrictions apply to source files that are to be
- compiled with `\cmdlineoption{-c}':
- \begin{itemize}
- \item
- term_expansion/2 should not use assert/1 and or retract/1 other than
- for local computational purposes.
- \item
- Files can only be included by the standard include directives: [...],
- consult/1, ensure_loaded/1 and use_module/[1,2]. User defined loading
- predicate invocations will not be compiled.
- \end{itemize}
- Directives are executed both when compiling the program and when
- loading the intermediate code file.
- \section{Environment Control}
- The current system defines 3 different mechanisms to query and/or set
- properties of the environment: please/3, flag/3 and feature/2 as well as
- a number of special purpose predicates of which unknown/2, fileerrors/2
- are examples. The ISO standard defines prolog_flag. It is likely that
- all these global features will be merged into a single in the future.
- \begin{description}
- \predicate{please}{3}{+Key, -Old, +New}
- The predicate please/3%
- \footnote{The idea comes from BIM_Prolog. The options supported by
- this predicate are not compatible with those for
- BIM_Prolog however.}
- is a solution to avoid large numbers of environment control
- predicates. Later versions will support other environment control as
- now provided via the predicates style_check/1, leash/1, unknown/2, the
- tracer predicates, etc. These predicates are then moved into a library
- for backwards compatibility. The currently available options are:
- \begin{description}
- \pleaseoption{optimise}{on/off}{off}
- Switch optimise mode for the compiler \const{on} or \const{off} (see also
- the command line option \cmdlineoption{-O}). Currently optimise compilation only
- implies compilation of arithmetic, making it fast, but invisible to the
- tracer. Later versions might imply various other optimisations such as
- incorporating a number of basic predicates in the virtual machine
- (var/1, fail/0, =/2, etc.) to gain speed at the cost of crippling the
- debugger. Also source level optimisations such as integrating small
- predicates into their callers, eliminating constant expressions and
- other predictable constructs. Source code optimisation is never
- applied to predicates that are declared dynamic (see dynamic/1).
- \pleaseoption{autoload}{on/off}{on}
- If \const{on} autoloading of library functions is enabled. If
- \const{off} autoloading is disabled. See \secref{autoload}.
- \pleaseoption{verbose_autoload}{on/off}{off}
- If \const{on} the normal consult message will be printed if a library is
- autoloaded. By default this message is suppressed. Intended to be used
- for debugging purposes (e.g.\ where does this predicate come from?).
- \end{description}
- \predicate{feature}{2}{?Key, -Value}
- The predicate feature/2 defines an interface to installation features:
- options compiled in, version, home, etc. With both arguments unbound,
- it will generate all defined features. With the `Key' instantiated it
- unify the value of the feature. Features come in three types: boolean
- features, features with an atom value and features with an integer
- value. A boolean feature is true iff the feature is present {\bf and}
- the \arg{Value} is the atom \const{true}. Currently defined keys:
- \begin{description}
- \featureoption{arch}{atom}
- Identifier for the hardware and operating system SWI-Prolog is running
- on. Used to determine the startup file as well as to select foreign
- files for the right architecture. See also load_foreign/5.
- \featureoption{version}{integer}
- The version identifier is an integer with value: $$10000 \times
- \arg{Major} + 100 \times \arg{Minor} + \arg{Patch}$$
- Note that in releases upto 2.7.10 this feature yielded an atom holding
- the three numbers separated by dots. The current representation is much
- easier for implementing version-conditional statements.
- \featureoption{home}{atom}
- SWI-Prolog's notion of the home-directory. SWI-Prolog uses it's home
- directory to find its startup file as \file{<home>/startup/startup.<arch>}
- and to find its library as \file{<home>/library}.
- \featureoption{pipe}{bool}
- If true, tell(pipe(command)), etc.\ are supported.
- \featureoption{load_foreign}{bool}
- If true, load_foreign/[2,5] are implemented.
- \featureoption{open_shared_object}{bool}
- If true, open_shared_object/2 and friends are implemented, providing
- access to shared libraries (.so files). This requires the C-library
- functions dlopen() and friends as well as the configuration option
- {\tt --with-dlopen}.
- \featureoption{dynamic_stacks}{bool}
- If true, the system uses some form of `sparse-memory management' to
- realise the stacks. If false, malloc()/realloc() are used for the stacks.
- In earlier days this had consequenses for foreign code. As of version
- 2.5, this is no longer the case.
- Systems using `sparse-memory management' are a bit faster as there is no
- stack-shifter, and checking the stack-boundary is often realised by the
- hardware using a `guard-page'. Also, memory is actually returned to the
- system after a garbage collection or call to trim_stacks/0 (called by
- prolog/0 after finishing a user-query).
- \featureoption{c_libs}{atom}
- Libraries passed to the C-linker when SWI-Prolog was linked. May be used
- to determine the libraries needed to create statically linked extensions
- for SWI-Prolog. See \secref{plld}.
- \featureoption{c_staticlibs}{atom}
- On some machines, the SWI-Prolog executable is dynamically linked, but
- requires some libraries to be statically linked. Obsolete.
- \featureoption{c_cc}{atom}
- Name of the C-compiler used to compile SWI-Prolog. Normally either gcc
- or cc. See \secref{plld}.
- \featureoption{c_ldflags}{atom}
- Special linker flags passed to link SWI-Prolog. See \secref{plld}.
- \featureoption{save}{bool}
- If true, save/[1,2] is implemented. Saving using save/0 is obsolete. See
- qsave_program/[1,2].
- \featureoption{save_program}{bool}
- If true, save_program/[1,2] is implemented. Saving using save_program/0
- is obsolete. See qsave_program/[1,2].
- \featureoption{readline}{bool}
- If true, SWI-Prolog is linked with the readline library. This is done
- by default if you have this library installed on your system. It is
- also true for the Win32 plwin.exe version of SWI-Prolog, which realises
- a subset of the readline functionality.
- \featureoption{saved_program}{bool}
- If true, Prolog is started from a state saved with qsave_program/[1,2].
- \featureoption{runtime}{bool}
- If true, SWI-Prolog is compiled with -DO_RUNTIME, disabling various
- useful development features (currently the tracer and profiler).
- \featureoption{max_integer}{integer}
- Maximum integer value. Most arithmetic operations will automatically
- convert to floats if integer values above this are returned.
- \featureoption{min_integer}{integer}
- Minimum integer value.
- \featureoption{max_tagged_integer}{integer}
- Maximum integer value represented as a `tagged' value. Tagged integers
- require 4-bytes storage and are used for indexing. Larger integers are
- represented as `indirect data' and require 16-bytes on the stacks (though
- a copy requires only 4 additional bytes).
- \featureoption{min_tagged_integer}{integer}
- Start of the tagged-integer value range.
- \featureoption{float_format}{atom}
- C {\tt printf()} format specification used by write/1 and friends to
- determine how floating point numbers are printed. The default is {\tt
- \%g}. May be changed. The specified value is passed to printf()
- without further checking. For example, if you want more digits printed,
- {\tt \%.12g} will print all floats using 12 digits instead of the
- default 6. See also format/[1,2], write/1, print/1 and portray/1.
- \featureoption{compiled_at}{atom}
- Describes when the system has been compiled. Only available if the
- C-compiler used to compile SWI-Prolog provides the __DATE__ and __TIME__
- macros.
- \featureoption{character_escapes}{bool}
- If true (default), read/1 interprets \verb$\$ escape sequences in quoted
- atoms and strings. May be changed.
- \featureoption{allow_variable_name_as_functor}{bool}
- If true (default is false), \exam{Functor(arg)} is read as if it was
- written \exam{'Functor'(arg)}. Some applications use the Prolog read/1
- predicate for reading an application defined script language. In these
- cases, it is often difficult to explain none-Prolog users of the
- application that constants and functions can only start with a lowercase
- letter. Variables can be turned into atoms starting with an uppercase
- atom by calling read_term/2 using the option \const{variable_names} and
- binding the variables to their name. Using this feature, F(x) can be
- turned into valid syntax for such script languages. Suggested by Robert
- van Engelen. SWI-Prolog specific.
- \featureoption{history}{integer}
- If $> 0$, support Unix \program{csh(1)} like history as described in
- \secref{history}. Otherwise, only support reusing commands through
- the commandline editor. The default is to set this feature to 0 if
- a commandline editor is provided (see feature \const{readline}) and
- 15 otherwise.
- \featureoption{gc}{bool}
- If true (default), the garbage collector is active. If false, neither
- garbage-collection, nor stack-shifts will take place, even not on
- explicit request. May be changed.
- \featureoption{trace_gc}{bool}
- If true (false is the default), garbage collections and stack-shifts
- will be reported on the terminal. May be changed.
- \featureoption{max_arity}{unbounded}
- ISO feature describing there is no maximum arity to compound terms.
- \featureoption{integer_rounding_function}{down,toward_zero}
- ISO feature describing rounding by \verb$//$ and \verb$rem$ arithmetic
- functions. Value depends on the C-compiler used.
- \featureoption{bounded}{true}
- ISO feature describing integer representation is bound by
- {\tt min_integer} and {\tt min_integer}.
- \featureoption{tty_control}{bool}
- Determines whether the terminal is switched to raw mode for
- get_single_char/1, which also reads the user-actions for the trace. May
- be set. See also the \cmdlineoption{+/-tty} command-line option.
- \featureoption{debug_on_error}{bool}
- If {\tt true}, start the tracer after an error is detected. Otherwise
- just continue execution. The goal that raised the error will normally
- fail. See also fileerrors/2 and the feature {\tt report_error}. May
- be changed. Default is {\tt true}, except for the runtime version.
- \featureoption{report_error}{bool}
- If {\tt true}, print error messages, otherwise suppress them. May be
- changed. See also the {\tt debug_on_error} feature. Default is {\tt
- true}, except for the runtime version.
- \featureoption{unix}{bool}
- \index{unix}%
- If {\tt true}, the operating system is some version of Unix. Defined
- if the C-compiler used to compile this version of SWI-Prolog either
- defines \verb$__unix__$ or \const{unix}.
- \featureoption{windows}{bool}
- \index{windows}%
- If {\tt true}, the operating system is an implementation of Microsoft
- Windows (3.1, 95, NT, etc.).
- \end{description}
- \predicate{set_feature}{2}{+Key, +Value}
- Define a new feature or change its value. \arg{Key} is an atom,
- \arg{Value} is an atom or number.
- \end{description}
- \section{Automatic loading of libraries} \label{sec:autoload}
- If ---at runtime--- an undefined predicate is trapped the system will
- first try to import the predicate from the module's default module.
- If this fails the \jargon{auto loader} is activated. On first activation
- an index to all library files in all library directories is loaded in
- core (see library_directory/1). If the undefined predicate can be
- located in the one of the libraries that library file is automatically
- loaded and the call to the (previously undefined) predicate is
- resumed. By default this mechanism loads the file silently. The
- please/3 option \const{verbose_autoload} is provided to get verbose
- loading. The please option \const{autoload} can be used to
- enable/disable the entire auto load system.
- Autoloading only handles (library) source files that use the module
- mechanism described in \chapref{modules}. The files are loaded
- with use_module/2 and only the trapped undefined predicate will be imported
- to the module where the undefined predicate was called. Each library
- directory must hold a file \file{INDEX.pl} that contains an index to all
- library files in the directory. This file consists of lines of the
- following format:
- \begin{code}
- index(Name, Arity, Module, File).
- \end{code}
- The predicate make/0 scans the autoload libraries and updates the
- index if it exists, is writable and out-of-date. It is advised to
- create an empty file called \file{INDEX.pl} in a library directory
- meant for auto loading before doing anything else. This index file
- can then be updated by running the prolog make_library_index/1 (`\%' is
- the Unix prompt):
- \begin{code}
- % mkdir ~/lib/prolog
- % cd !$
- % pl -g true -t 'make_library_index(.)'
- \end{code}
- If there are more than one library files containing the desired predicate
- the following search schema is followed:
- \begin{enumerate}
- \item If a there is a library file that defines the module in which
- the undefined predicate is trapped, this file is used.
- \item Otherwise library files are considered in the order they appear
- in the library_directory/1 predicate and within the directory
- alphabetically.
- \end{enumerate}
- \begin{description}
- \predicate{make_library_index}{1}{+Directory}
- Create an index for this directory. The index is written to the file
- 'INDEX.pl' in the specified directory. Fails with a warning if the
- directory does not exist or is write protected.
- \end{description}
- \subsection{Notes on Automatic Loading}
- The autoloader is a new feature to SWI-Prolog. Its aim is to simplify
- program development and program management. Common lisp has a similar
- feature, but here the user has to specify which library is to be
- loaded if a specific function is called which is not defined. The
- advantage of the SWI-Prolog schema is that the user does not have to
- specify this. The disadvantage however is that the user might be
- wondering ``where the hell this predicate comes from''. Only
- experience can learn whether the functionality of the autoloader is
- appropriate. Comments are welcome.
- The autoloader only works if the unknown flag (see unknown/2) is set to
- \const{trace} (default). A more appropriate interaction with this flag
- will be considered.
- \section{Garbage Collection}
- SWI-Prolog version 1.4 was the first release to support garbage
- collection. Together with tail-recursion optimisation this guaranties
- forward chaining programs do not waste indefinite amounts of memory.
- Previous releases of this manual stressed on using failure-driven
- loops in those cases that no information needed to be passed to the
- next iteration via arguments. This to avoid large amounts of garbage.
- This is no longer strictly necessary, but it should be noticed that
- garbage collection is a time consuming activity. Failure driven loops
- tend to be faster for this reason.
- \section{Syntax Notes}
- SWI-Prolog uses standard `Edinburgh' syntax. A description of this
- syntax can be found in the Prolog books referenced in the introduction.
- Below are some non-standard or non-common constructs that are accepted
- by SWI-Prolog:
- \begin{itemlist}
- \item [\exam{0'<char>}]
- This construct is not accepted by all Prolog systems that claim to have
- Edinburgh compatible syntax. It describes the ASCII value of <char>.
- To test whether \chr{C} is a lower case character one can use
- \exam{between(0'a, 0'z, C)}.
- \item [\exam{/* \ldots /* \ldots */ \ldots */}]
- The \exam{/* \ldots */} comment statement can be nested. This is useful
- if some code with \exam{/* \ldots */} comment statements in it should be
- commented out.
- \end{itemlist}
- \subsection{ISO Syntax Support}
- SWI-Prolog offers ISO compatible extensions to the Edinburgh syntax.
- \subsubsection{Character Escape Syntax} \label{sec:charescapes}
- Within quoted atoms (using single quotes: \exam{'<atom>'} special
- characters are represented using escape-sequences. An escape sequence
- is lead in by the backslash (\chr{\}) character. The list of
- escape sequences is compatible with the ISO standard, but contains one
- extension and the interpretation of numerically specified characters is
- slightly more flexible to improve compatibility.
- \begin{description}
- \escapeitem{a}
- Alert character. Normally the ASCII character 7 (beep).
- \escapeitem{b}
- Backspace character.
- \escapeitem{c}
- No output. All input characters upto but not including the first
- non-layout character are skipped. This allows for the specification
- of pretty-looking long lines. For compatibility with Quintus Prolog.
- Nor supported by ISO. Example:
- \begin{code}
- format('This is a long line that would look better if it was \c
- split across multiple physical lines in the input')
- \end{code}
- \escapeitem{\bnfmeta{{\sc RETURN}}}
- No output. Skips input till the next non-layout character or to the
- end of the next line. Same intention as \fmtseq{\c} but ISO compatible.
- \escapeitem{f}
- Form-feed character.
- \escapeitem{n}
- Next-line character.
- \escapeitem{r}
- Carriage-return only (i.e.\ go back to the start of the line).
- \escapeitem{t}
- Horizontal tab-character.
- \escapeitem{v}
- Vertical tab-character (ASCII 11).
- \escapeitem{x23}
- Hexadecimal specification of a character. \verb$23$ is just an example.
- The `x' may be followed by a maximum of 2 hexadecimal digits. The
- closing \verb$\$ is optional. The code \verb$\xa\3$ emits the character
- 10 (hexadecimal `a') followed by `3'. The code \verb$\x201$ emits
- 32 (hexadecimal `20') followed by `1'. According to ISO, the closing
- \verb$\$ is obligatory and the number of digits is unlimited. The
- SWI-Prolog definition allows for ISO compatible specification, but
- is compatible with other implementations.
- \escapeitem{40}
- Octal character specification. The rules and remarks for hexadecimal
- specifications apply to octal specifications too, but the maximum
- allowed number of octal digits is 3.
- \escapeitem{<character>}
- Any character immediately preceded by a \chr{\} is copied verbatim.
- Thus, \verb$'\\'$ is an atom consisting of a single \chr{\} and
- \verb$'\''$ and \verb$''''$ both describe the atom with a
- single~\verb$'$.
- \end{description}
- Character escaping is only available if the
- \exam{feature(character_escapes, true)} is active (default). See
- feature/2. Character escapes conflict with writef/2 in two ways:
- \verb$\40$ is interpreted as decimal 40 by writef/2, but character
- escapes handling by read has already interpreted as 32 (40 octal). Also,
- \fmtseq{\l} is translated to a single `l'. Double the \chr{\}
- (e.g.\ \fmtseq{\\}, use the above escape sequences or use format/2.
- \subsubsection{Syntax for Non-Decimal Numbers}
- SWI-Prolog implements both Edinburgh and ISO representations for
- non-decimal numbers. According to Edinburgh syntax, such numbers are
- written as \exam{<radix>'<number>}, where <radix> is a number between 2
- and 36. ISO defines binary, octal and hexadecimal numbers using
- \exam{0{\em [bxo]}<number>}. For example: \verb$A is 0b100 \/ 0xf00$ is
- a valid expression. Such numbers are always unsigned.
- \section{System Limits}
- \subsection{Limits on Memory Areas}
- SWI-Prolog has a number of memory areas which are only enlarged to a
- certain limit. The default sizes for these areas should suffice for most
- applications, but big applications may require larger ones. They are
- modified by command line options. The table below shows these areas. The
- first column gives the option name to modify the size of the area. The
- option character is immediately followed by a number and optionally by a
- \const{k} or \const{m}. With \const{k} or no unit indicator, the value
- is interpreted in Kbytes (1024 bytes), with \const{m}, the value is
- interpreted in Mbytes ($1024 \times 1024$ bytes).
- The local-, global- and trail-stack are limited to 64 Mbytes on 32 bit
- processors, or more in general to $\pow{2}{\mbox{bits-per-long} - 6}$
- bytes.
- \begin{table}
- \begin{center}
- \begin{tabular}{|c|c|l|p{5cm}|}
- \hline
- Option & Default & Area name & Description \\
- \hline
- \cmdlineoption{-L} & 2M & \bf local stack & The local stack is used to store
- the execution environments of procedure
- invocations. The space for an environment is
- reclaimed when it fails, exits without leaving
- choice points, the alternatives are cut of with
- the !/0 predicate or no choice points have
- been created since the invocation and the last
- subclause is started (tail recursion optimisation). \\
- \cmdlineoption{-G} & 4M & \bf global stack & The global stack is used
- to store terms created during Prolog's
- execution. Terms on this stack will be reclaimed
- by backtracking to a point before the term
- was created or by garbage collection (provided the
- term is no longer referenced). \\
- \cmdlineoption{-T} & 4M & \bf trail stack & The trail stack is used to store
- assignments during execution. Entries on this
- stack remain alive until backtracking before the
- point of creation or the garbage collector
- determines they are nor needed any longer. \\
- \cmdlineoption{-A} & 1M & \bf argument stack & The argument stack is used to
- store one of the intermediate code interpreter's
- registers. The amount of space needed on this
- stack is determined entirely by the depth in
- which terms are nested in the clauses that
- constitute the program. Overflow is most likely
- when using long strings in a clause. \\
- \hline
- \end{tabular}
- \end{center}
- \caption{Memory areas}
- \label{tab:areas}
- \end{table}
- \subsubsection{The heap} \label{sec:heap}
- \index{stack,memory management}%
- \index{memory,layout}%
- With the heap, we refer to the memory area used by \funcref{malloc}{}
- and friends. SWI-Prolog uses the area to store atoms, functors,
- predicates and their clauses, records and other dynamic data. As of
- SWI-Prolog 2.8.5, no limits are imposed on the addresses returned by
- \funcref{malloc}{} and friends.
- On some machines, the runtime stacks described above are allocated using
- `sparse allocation'. Virtual space upto the limit is claimed at startup
- and committed and released while the area grows and shrinks. On Win32
- platform this is realised using \funcref{VirtualAlloc}{} and friends.
- On Unix systems this is realised using \funcref{mmap}{}, either mapping
- \file{/dev/zero} or a temporary file created in \file{/tmp}.
- As Unix provides no way to reserve part of the address space, this
- process may lead to conflicts. By default, SWI-Prolog computes the
- required virtual address space for the runtime stacks. If available, it
- uses \funcref{getrlimit}{} to determine the top of the virtual space
- reserved for \funcref{malloc}{} usage and locates the stacks in the top
- of this area. It assumes no other \funcref{mmap}{} activity such as
- mapping shared libraries or \funcref{mmap}{} by foreign modules will use
- the area reserved for the heap and \funcref{malloc}{},
- \funcref{malloc}{} will grow the heap from low to high addresses and
- will notice the existence of the Prolog stacks.
- These assumptions appear to hold. The user may using the
- \cmdlineoption{-H} to specify the maximum heap-size. In this case,
- the Prolog stacks will be allocated at the indicated size from the
- current top of the heap. On these system, statistics/[0,2] reports
- \idx{heaplimit} and \idx{heap}. The \idx{heaplimit} value is the
- distance between the {\em break} and the first Prolog stack.
- The \idx{heap} value is the distance between what Prolog assumes to
- be the base of the heap%
- \footnote{There is no portable and reliable way to find the real
- base.}
- and the current location of the break.
- \subsection{Other Limits}
- \begin{description}
- \item[Clauses]
- Currently the following limitations apply to clauses. The arity may
- not be more than 1024 and the number of variables should be less than
- 65536.
- \item[Atoms and Strings]
- SWI-Prolog has no limits on the sizes of atoms and strings. read/1 and
- its derivatives however normally limit the number of newlines in an atom
- or string to 5 to improve error detection and recovery. This can be
- switched off with style_check/1.
- \item[Address space]
- SWI-Prolog data is packed in a 32-bit word, which contains both type
- and value information. The size of the various memory areas is limited
- to 128 Mb for each of the areas. With some redesign, the program area
- could be split into data that should be within this range and the rest
- of the data, virtually unlimiting the program size.
- \item[Integers]
- Integers are 32-bit to the user, but integers upto the value of the
- {\tt max_tagged_integer} feature are represented more efficiently.
- \item[Floats]
- Floating point numbers are represented as native double precision
- floats, 64 bit IEEE on most machines.
- \end{description}
- \subsection{Reserved Names}
- The boot compiler (see \cmdlineoption{-b} option) does not support the module
- system (yet). As large parts of the system are written in Prolog itself
- we need some way to avoid name clashes with the user's predicates,
- database keys, etc. Like Edinburgh C-Prolog \cite{CPROLOG:manual} all
- predicates, database keys, etc.\ that should be hidden from the user
- start with a dollar (\chr{\$}) sign (see style_check/1).
- The compiler uses the special functor \const{\$VAR\$/1} while analysing the
- clause to compile. Using this functor in a program causes unpredictable
- behaviour of the compiler and resulting program.
-